package com.zzb.framework.user.dao;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zzb.framework.user.dao.mapper.UserMapper;
import com.zzb.framework.user.entity.User;
import com.zzb.framework.common.BaseDAO;
import com.zzb.framework.common.DAOException;
import com.zzb.framework.utils.Misc;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户账号 Dao接口
 */
@Repository
public class UserDAO extends BaseDAO<User> {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserMapper getMapper() {
        return userMapper;
    }

    /**
     * 通过用户登录名查找符合的用户数量
     */
    public long countUserByLoginName(String name) {
        return getMapper().selectCount(new EntityWrapper<User>().eq("login_name", name));
    }

    /**
     * 通过用户名和密码查找查找
     */
    public User getByLoginNameAndPassword(String name, String password) throws DAOException {
        List<User> users = getMapper().selectList(new EntityWrapper<User>()
                .eq("login_name", name)
                .eq("password", Misc.generatePassword(password)));
        if (CollectionUtils.size(users) == 0) {
            throw new DAOException("用户账号或密码错误");
        } else if (CollectionUtils.size(users) != 1) {
            throw new DAOException("用户存在异常现象，请联系管理员吧");
        }
        return users.get(0);
    }

    public List<User> findByLoginName(String loginName) {
        return getMapper().selectList(new EntityWrapper<User>()
                .eq("login_name", loginName));
    }

    @Override
    public List<User> selectAll() {
        return getMapper().selectList(new EntityWrapper<User>()
                .orderBy("create_time", false));
    }
}
